package com.xuxin.baby.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.lxj.xpopup.XPopup;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.xuxin.baby.R;
import com.xuxin.baby.adapter.CartAdapter;
import com.xuxin.baby.base.BaseActivity;
import com.xuxin.baby.base.BaseConstant;
import com.xuxin.baby.database.DBControl;
import com.xuxin.baby.popup.ConfirmPopup;
import com.xuxin.baby.utils.ACache;
import com.xuxin.baby.utils.RecycleUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by xu_xin
 * Created on 2020.08.05 0005
 * 我的购物车
 */
public class UserCartActivity extends BaseActivity {
    @BindView(R.id.title_left)
    ImageView title_left;
    @BindView(R.id.title_right)
    ImageView title_right;
    @BindView(R.id.title_name)
    TextView title_name;
    @BindView(R.id.cart_status)
    RelativeLayout cart_status;
    @BindView(R.id.cart_select)
    CheckBox cart_select;//全选
    @BindView(R.id.cart_price)
    TextView cart_price;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout smart_refresh;
    @BindView(R.id.smart_recycle)
    RecyclerView smart_recycle;

    private CartAdapter myAdapter;
    private String memberId;//用户id
    private String tenantId;//租户id
    private String token;//授权token

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_cart);
    }

    @Override
    public void initView() {
        title_name.setText("我的购物车");
        title_right.setImageBitmap(ImageUtils.getBitmap(R.mipmap.img_delete));
        title_right.setVisibility(View.VISIBLE);
        smart_refresh.setEnableLoadMore(false);
        smart_refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                myAdapter.setList(DBControl.queryCart());
                onComplete();
            }
        });
        RecycleUtils.init(smart_recycle);
        myAdapter = new CartAdapter();
        smart_recycle.setAdapter(myAdapter);
        myAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                boolean isCheck = myAdapter.getData().get(position).isCheck();
                myAdapter.getData().get(position).setCheck(!isCheck);
                myAdapter.notifyDataSetChanged();
                summary();
            }
        });
        cart_select.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean check) {
                check(check);
            }
        });
    }

    @Override
    public void initData() {
        ACache aCache = ACache.get(this);
        memberId = aCache.getAsString(BaseConstant.memberId);
        tenantId = aCache.getAsString(BaseConstant.tenantId);
        token = aCache.getAsString(BaseConstant.token);
        smart_refresh.autoRefresh();
    }

    @Override
    public void onComplete() {
        dismiss();
        smart_refresh.finishRefresh();
        smart_refresh.finishLoadMore();
        if (myAdapter.getData().size() > 0) {
            cart_status.setVisibility(View.VISIBLE);
        } else {
            cart_status.setVisibility(View.GONE);
        }
    }

    @Override
    @OnClick({R.id.title_left, R.id.title_right, R.id.cart_payment})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.title_left) {
            finish();
        } else if (id == R.id.title_right) {
            if (hasCheck) {
                new XPopup.Builder(context)
                        .dismissOnTouchOutside(true)
                        .dismissOnBackPressed(true)
                        .asCustom(new ConfirmPopup(context, "确定要删除商品吗？", new ConfirmPopup.OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                try {
                                    popup.setTitle("正在删除中...").show();
                                    delete();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    dismiss();
                                }
                            }
                        })).show();
            } else {
                ToastUtils.showShort("没有选择商品");
            }
        } else if (id == R.id.cart_payment) {
            if (hasCheck) {
                JSONObject order = getOrderCommit();
                if (null != order) {
                    Bundle bundle = new Bundle();
                    bundle.putString("order", order.toString());
                    ActivityUtils.startActivityForResult(bundle, UserCartActivity.this, OrderCommitActivity.class, 200, bundle);
                }
            } else {
                ToastUtils.showShort("没有选择商品");
            }
        }
    }

    /**
     * 全选按钮
     */
    private void check(boolean check) {
        for (int i = 0; i < myAdapter.getData().size(); i++) {
            myAdapter.getData().get(i).setCheck(check);
        }
        myAdapter.notifyDataSetChanged();
        summary();
    }

    /**
     * 合计价格
     */
    private boolean hasCheck;
    private float price = 0;

    private void summary() {
        price = 0;
        hasCheck = false;
        for (int i = 0; i < myAdapter.getData().size(); i++) {
            if (myAdapter.getData().get(i).isCheck()) {
                price = price + myAdapter.getData().get(i).getPrice();
                hasCheck = true;
            }
        }
        cart_price.setText(String.valueOf(price));
    }

    /**
     * 删除选中
     */
    private void delete() {
        for (int i = 0; i < myAdapter.getData().size(); i++) {
            if (myAdapter.getData().get(i).isCheck()) {
                DBControl.deleteCartById(myAdapter.getData().get(i).getId());
            }
        }
        myAdapter.setList(DBControl.queryCart());
        onComplete();
    }

    private JSONObject getOrderCommit() {
        try {
            JSONObject order = new JSONObject();
            JSONArray details = new JSONArray();
            order.put("memberId", memberId);
            order.put("orderType", null);
            order.put("tradeType", "trade");
            order.put("summary", price);
            for (int i = 0; i < myAdapter.getData().size(); i++) {
                if (myAdapter.getData().get(i).isCheck()) {
                    JSONObject detail = new JSONObject();
                    detail.put("productId", myAdapter.getData().get(i).getUid());
                    detail.put("OrderQty", 1);
                    detail.put("UnitPrice", 0);
                    detail.put("UnitBean", myAdapter.getData().get(i).getPrice());
                    detail.put("title", myAdapter.getData().get(i).getTitle());
                    detail.put("content", myAdapter.getData().get(i).getContent());
                    detail.put("image", myAdapter.getData().get(i).getImage());
                    details.put(detail);
                }
            }
            order.put("details", details);
            return order;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200 && resultCode == 200) {
            delete();
        }
    }
}